package com.nacos.gateway.predicate;

import com.nacos.gateway.bean.TimeBetweenConfig;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
/**
 * 第一步:写一个自定义谓词工厂，类名必须要以RoutePredicateFactory结尾 然后继承AbstractRoutePredicateFactory TimeBetween{}.java
 * 第二步:书写一个配置类,用于接受配置 TimeBetweenConfig.java
 * 第三步:在yml配置中【谓词配置是以我们自定义类名，去除了RoutePredicateFactory】
 */
@Component
public class TimeBetweenRoutePredicateFactory extends AbstractRoutePredicateFactory<TimeBetweenConfig> {

    public TimeBetweenRoutePredicateFactory() {
        super(TimeBetweenConfig.class);
    }
    /**
     * 实现方法 参考 AbstractRoutePredicateFactory的实现类
     * @param config
     * @return
     */
    @Override
    public Predicate<ServerWebExchange> apply(TimeBetweenConfig config) {
        LocalTime startTime = config.getStartTime();
        LocalTime endTime = config.getEndTime();
        return new Predicate<ServerWebExchange>(){
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                LocalTime now = LocalTime.now();
                Boolean flag = now.isAfter(startTime) && now.isBefore(endTime);
                System.out.println("开始时间："+startTime+" 结束时间："+endTime+" now："+now+" flag："+flag);
                return flag;
            }
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("startTime", "endTime");
    }
}
